package com.kordar.rbac;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Slf4j
@Configuration
@EnableConfigurationProperties(RbacProperties.class)
@ConditionalOnProperty(prefix = "kordar.rbac", name = "active", havingValue = "true")
public class RbacConfig {

    final
    AuthManagerMapper authManagerMapper;

    final
    RbacProperties rbacProperties;

    @Autowired
    public RbacConfig(AuthManagerMapper authManagerMapper, RbacProperties rbacProperties) {
        this.authManagerMapper = authManagerMapper;
        this.rbacProperties = rbacProperties;
    }

    @Bean
    public AuthManager authManager() {
        DbAuthManager authManager = new DbAuthManager(authManagerMapper);
        if (StringUtils.hasText(rbacProperties.getDefaultRole())) {
            Role role = authManager.createRole(rbacProperties.getDefaultRole());
            authManager.setDefaultRoles(role);
            log.info("written '" + role.getName() + "' for the default role!");
            if (!rbacProperties.getDefaultPermissions().isEmpty()) {
                for (String name : rbacProperties.getDefaultPermissions()) {
                    Permission child = authManager.createPermission(name);
                    try {
                        if (authManager.add(child) && authManager.canAddChild(role, child)) {
                            authManager.addChild(role, child);
                            log.info("added permission " + child.getName() + " to the role " + role.getName());
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
        return authManager;
    }
}
